import qs from "qs";
import {onActivated, onMounted} from "vue";

import {ElMessage, ElMessageBox} from "element-plus";
import {useI18n} from "vue-i18n";
import {IObject, IViewHooks, IViewHooksOptions} from "/@/types/interface";
import Api from "/@/api/Api";
import Cookies from "js-cookie";
import {download} from "/@/utils/utils";
import {useDictStore} from "/@/stores/dict";

/**
 * 通用视图业务逻辑（列表/增删改查基本业务）
 * @param props 自定义通用业务state
 * @returns 返回响应式自定义state和通用方法
 */
const useView = (props: IViewHooksOptions | IObject): IViewHooks => {
    const {t} = useI18n();
    const defaultOptions: IViewHooksOptions = {
        createdIsNeed: true,
        activatedIsNeed: false,
        getDataListURL: "",
        getDataListIsPage: false,
        deleteURL: "",
        deleteIsBatch: false,
        deleteIsBatchKey: "id",
        exportURL: "",
        dataForm: {},
        dataList: [],
        order: "",
        orderField: "",
        page: 1,
        limit: 10,
        total: 0,
        dataListLoading: false,
        dataListSelections: [],
        elTable: {}
    };
    const mergeDefaultStateToPageState = (options: IObject, props: IObject): IViewHooksOptions => {
        for (const key in options) {
            if (!Object.getOwnPropertyDescriptor(props, key)) {
                props[key] = options[key];
            }
        }
        return props;
    };
    const state = mergeDefaultStateToPageState(defaultOptions, props);
    onMounted(() => {
        if (state.createdIsNeed && !state.activatedIsNeed) {
            viewFns.query();
        }
    });
    onActivated(() => {
        if (state.activatedIsNeed) {
            viewFns.query();
        }
    });

    //
    const rejectFns = {

        getDictLabel(dictType: string, dictValue: string) {
            return useDictStore().getDict(dictType).find(item=>{
                return item.value=dictValue
            });
        }
    };

    //
    const viewFns = {
        // 获取数据列表
        query() {
            if (!state.getDataListURL) {
                return;
            }
            state.dataListLoading = true;
            Api
                .get({
                    url: state.getDataListURL,
                    params: {
                        order: state.order,
                        orderField: state.orderField,
                        page: state.getDataListIsPage ? state.page : null,
                        limit: state.getDataListIsPage ? state.limit : null,
                        ...state.dataForm
                    }
                })
                .then((res) => {
                    state.dataListLoading = false;
                    state.dataList = state.getDataListIsPage ? res.data.records : res.data;
                    state.total = state.getDataListIsPage ? res.data.total : 0;
                })
                .catch(() => {
                    state.dataListLoading = false;
                });
        },
        // 多选
        dataListSelectionChangeHandle(val: IObject[]) {
            state.dataListSelections = val;
        },
        // 排序
        dataListSortChangeHandle(data: IObject) {
            if (!data.order || !data.prop) {
                state.order = "";
                state.orderField = "";
                return false;
            }
            state.order = data.order.replace(/ending$/, "");
            state.orderField = data.prop.replace(/([A-Z])/g, "_$1").toLowerCase();
            viewFns.query();
        },
        // 分页, 每页条数
        pageSizeChangeHandle(val: number) {
            state.page = 1;
            state.limit = val;
            viewFns.query();
        },
        // 分页, 当前页
        pageCurrentChangeHandle(val: number) {
            state.page = val;
            viewFns.query();
        },
        //搜索
        getDataList() {
            state.page = 1;
            viewFns.query();
        },
        // 删除
        deleteHandle(id?: string): Promise<any> {
            return new Promise((resolve, reject) => {
                if (
                    state.deleteIsBatch &&
                    !id &&
                    state.dataListSelections &&
                    state.dataListSelections.length <= 0
                ) {
                    ElMessage.warning({
                        message: "请选择操作项",
                        duration: 500
                    });
                    return;
                }
                ElMessageBox.confirm("确定进行[删除]操作?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {

                        let ids = state.deleteIsBatch ? id : state.dataListSelections?.join(",")
                        Api.delete({
                            url: `${state.deleteURL}`, params: {ids: ids}
                        })
                            .then((res) => {
                                ElMessage.success({
                                    message: "成功",
                                    duration: 500,
                                    onClose: () => {
                                        viewFns.query();
                                        resolve(true);
                                    }
                                });
                            });
                    })
                    .catch(() => {
                        //
                    });
            });
        },
        // 导出
        exportHandle() {
            // window.location.href = `boot-admin${state.exportURL}?${qs.stringify({
            //     ...state.dataForm,
            //     saToken: Cookies.get('token')
            // })}`;
            if (state.exportURL !== undefined) {
                download(state.exportURL, new Date().toString())
            }
        },
    };

    //
    return {
        ...viewFns,
        ...rejectFns
    };
};

export default useView;
